const express = require('express');
const User = require('../models/User');
const router = express.Router();

/**
 * 用户登录
 */
router.post('/login', async (req, res) => {
  try {
    const { phone, token, refreshToken, userInfo } = req.body;
    
    if (!phone || !token) {
      return res.status(400).json({
        code: '40000',
        message: '手机号和token不能为空',
        data: null
      });
    }
    
    // 保存或更新用户信息
    const userData = {
      phone,
      token,
      refresh_token: refreshToken,
      nickname: userInfo?.nickname,
      avatar_url: userInfo?.avatar,
      city: userInfo?.city,
      province: userInfo?.province,
      latitude: userInfo?.latitude,
      longitude: userInfo?.longitude
    };
    
    const result = await User.upsert(userData);
    
    res.json({
      code: '20000',
      message: '登录成功',
      data: {
        userId: result.userId,
        phone: result.phone,
        action: result.action
      }
    });
    
  } catch (error) {
    console.error('登录失败:', error);
    res.status(500).json({
      code: '50000',
      message: '登录失败',
      data: null
    });
  }
});

/**
 * 用户登出
 */
router.post('/logout', async (req, res) => {
  try {
    const { phone } = req.body;
    
    if (phone) {
      await User.updateToken(phone, null, null);
    }
    
    res.json({
      code: '20000',
      message: '登出成功',
      data: null
    });
    
  } catch (error) {
    console.error('登出失败:', error);
    res.status(500).json({
      code: '50000',
      message: '登出失败',
      data: null
    });
  }
});

/**
 * 验证token
 */
router.post('/verify', async (req, res) => {
  try {
    const { token } = req.body;
    
    if (!token) {
      return res.status(400).json({
        code: '40000',
        message: 'Token不能为空',
        data: null
      });
    }
    
    const user = await User.verifyToken(token);
    
    if (!user) {
      return res.status(401).json({
        code: '40100',
        message: 'Token无效',
        data: null
      });
    }
    
    res.json({
      code: '20000',
      message: 'Token有效',
      data: {
        userId: user.id,
        phone: user.phone,
        nickname: user.nickname
      }
    });
    
  } catch (error) {
    console.error('Token验证失败:', error);
    res.status(500).json({
      code: '50000',
      message: 'Token验证失败',
      data: null
    });
  }
});

module.exports = router;
